package flc.ast.fragment;

import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EdgeEffect;
import android.widget.ImageView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.hpplay.sdk.source.api.IConnectListener;
import com.hpplay.sdk.source.browse.api.IBrowseListener;
import com.hpplay.sdk.source.browse.api.LelinkServiceInfo;
import com.stark.cast.screen.CastScreenManager;
import com.stark.picselect.entity.SelectMediaEntity;

import java.util.ArrayList;
import java.util.List;

import flc.ast.AppConfig;
import flc.ast.R;
import flc.ast.activity.SelAudioActivity;
import flc.ast.activity.SelPicActivity;
import flc.ast.activity.SelVideoActivity;
import flc.ast.adapter.AudioRecordAdapter;
import flc.ast.adapter.DeviceAdapter;
import flc.ast.adapter.PicRecordAdapter;
import flc.ast.adapter.VideoRecordAdapter;
import flc.ast.bean.MyCollectBean;
import flc.ast.databinding.FragmentProBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.FastClickUtil;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ProFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ProFragment extends BaseNoModelFragment<FragmentProBinding> {

    private CastScreenManager mCastScreenManager;
    private boolean isSearch = false;
    private DeviceAdapter deviceAdapter;
    private int oldPosition;
    private VideoRecordAdapter videoRecordAdapter;
    private PicRecordAdapter picRecordAdapter;
    private AudioRecordAdapter audioRecordAdapter;
    private int type=0;
    private Dialog myClearDialog;



    @Override
    protected int onCreate() {
        return R.layout.fragment_pro;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);
        mDataBinding.llSearch.setOnClickListener(this);
        mDataBinding.ivSelVideo.setOnClickListener(this);
        mDataBinding.ivSelPic.setOnClickListener(this);
        mDataBinding.ivSelAudio.setOnClickListener(this);
        mDataBinding.llVideoRecord.setOnClickListener(this);
        mDataBinding.llPicRecord.setOnClickListener(this);
        mDataBinding.llAudioRecord.setOnClickListener(this);
        mDataBinding.tvClear.setOnClickListener(this);
        mDataBinding.rvDeviceList.setLayoutManager(new LinearLayoutManager(mContext,LinearLayoutManager.VERTICAL,false));
        deviceAdapter=new DeviceAdapter();
        mDataBinding.rvDeviceList.setAdapter(deviceAdapter);
        deviceAdapter.addChildClickViewIds(R.id.ivDeviceItemSel);
        deviceAdapter.setOnItemChildClickListener(this);
        mDataBinding.rvVideoList.setLayoutManager(new GridLayoutManager(mContext,3));
        videoRecordAdapter=new VideoRecordAdapter();
        mDataBinding.rvVideoList.setAdapter(videoRecordAdapter);
        mDataBinding.rvPicList.setLayoutManager(new GridLayoutManager(mContext,3));
        picRecordAdapter=new PicRecordAdapter();
        mDataBinding.rvPicList.setAdapter(picRecordAdapter);
        mDataBinding.rvAudioList.setLayoutManager(new GridLayoutManager(mContext,3));
        audioRecordAdapter=new AudioRecordAdapter();
        mDataBinding.rvAudioList.setAdapter(audioRecordAdapter);
        //注册投屏
        registerScreen();
        //清空弹框
        clearDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        if (FastClickUtil.isFastClick()) return;
        switch (v.getId()){
            case R.id.llSearch://搜索
                if (isSearch) return;
                isSearch=true;
                showDialog(getString(R.string.search_ing));
                mCastScreenManager.startBrowse();
                break;
            case R.id.ivSelVideo://视频投屏
                if (!Content.IsConnect) {
                    ToastUtils.showShort(R.string.please_conn_pro_device);
                    return;
                }
                SelVideoActivity.isMoreSel=true;
                startActivity(SelVideoActivity.class);
                break;
            case R.id.ivSelPic://图片投屏
                gotoPro(SelPicActivity.class);
                break;
            case R.id.ivSelAudio://音频投屏
                gotoPro(SelAudioActivity.class);
                break;
            case R.id.llVideoRecord://视频记录
                clearSelection();
                mDataBinding.tvVideoRecord.setTypeface(Typeface.DEFAULT_BOLD);
                mDataBinding.tvVideoRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivVideoRecord.setVisibility(View.VISIBLE);
                mDataBinding.rlVideoRecord.setVisibility(View.VISIBLE);
                getVideoData();
                type=0;
                break;
            case R.id.llPicRecord://图片记录
                clearSelection();
                mDataBinding.tvPicRecord.setTypeface(Typeface.DEFAULT_BOLD);
                mDataBinding.tvPicRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivPicRecord.setVisibility(View.VISIBLE);
                mDataBinding.rlPicRecord.setVisibility(View.VISIBLE);
                getPicData();
                type=1;
                break;
            case R.id.llAudioRecord://音频记录
                clearSelection();
                mDataBinding.tvAudioRecord.setTypeface(Typeface.DEFAULT_BOLD);
                mDataBinding.tvAudioRecord.setTextColor(Color.parseColor("#FFFFFF"));
                mDataBinding.ivAudioRecord.setVisibility(View.VISIBLE);
                mDataBinding.rlAudioRecord.setVisibility(View.VISIBLE);
                getAudioData();
                type=2;
                break;
            case R.id.tvClear://清空
                myClearDialog.show();
                break;
            case R.id.ivDialogClearCancel://清空弹框
                myClearDialog.dismiss();
                break;
            case R.id.ivDialogClearConfirm:
                if (type==0){
                    List<SelectMediaEntity> list=new ArrayList<>();
                    AppSpUtils.saveVideoList(list);
                    getVideoData();
                }else if (type==1){
                    List<SelectMediaEntity> list=new ArrayList<>();
                    AppSpUtils.savePictureList(list);
                    getPicData();
                }else if (type==2){
                    List<AudioBean> list=new ArrayList<>();
                    AppSpUtils.saveAudioList(list);
                    getAudioData();
                }
                myClearDialog.dismiss();
                break;
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        switch (view.getId()){
            case R.id.ivDeviceItemSel:
                if (deviceAdapter.getItem(position).isConnect()) {
                    Content.IsConnect = false;
                    deviceAdapter.getItem(position).setConnect(false);
                    deviceAdapter.notifyDataSetChanged();
                    mCastScreenManager.disConnect();
                    Content.ConnectName = "";
                } else {
                    Content.IsConnect = true;
                    deviceAdapter.getItem(oldPosition).setConnect(false);
                    oldPosition=position;
                    deviceAdapter.getItem(position).setConnect(true);
                    deviceAdapter.notifyDataSetChanged();
                    mCastScreenManager.connect(deviceAdapter.getItem(position));
                    Content.ConnectName = deviceAdapter.getItem(position).getName();
                }
                break;
        }
    }

    @Override
    protected void initData() {
        getVideoData();
    }

    private void getVideoData(){
        List<SelectMediaEntity> listSp = AppSpUtils.getVideoList();
        if (listSp != null && listSp.size() > 0) {
            videoRecordAdapter.setList(listSp);
            mDataBinding.rvVideoList.setVisibility(View.VISIBLE);
            mDataBinding.tvVideoNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvVideoList.setVisibility(View.GONE);
            mDataBinding.tvVideoNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getPicData(){
        List<SelectMediaEntity> listSp = AppSpUtils.getPictureList();
        if (listSp != null && listSp.size() > 0) {
            picRecordAdapter.setList(listSp);
            mDataBinding.rvPicList.setVisibility(View.VISIBLE);
            mDataBinding.tvPicNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvPicList.setVisibility(View.GONE);
            mDataBinding.tvPicNoData.setVisibility(View.VISIBLE);
        }
    }

    private void getAudioData(){
        List<AudioBean> listSp = AppSpUtils.getAudioList();
        if (listSp != null && listSp.size() > 0) {
            audioRecordAdapter.setList(listSp);
            mDataBinding.rvAudioList.setVisibility(View.VISIBLE);
            mDataBinding.tvAudioNoData.setVisibility(View.GONE);
        } else {
            mDataBinding.rvAudioList.setVisibility(View.GONE);
            mDataBinding.tvAudioNoData.setVisibility(View.VISIBLE);
        }
    }

    //去到投屏界面
    private void gotoPro(Class cls) {
        if (!Content.IsConnect) {
            ToastUtils.showShort(R.string.please_conn_pro_device);
            return;
        }
        startActivity(cls);
    }

    //注册投屏
    private void registerScreen() {
        CastScreenManager.init(AppConfig.TEST_APP_ID, AppConfig.TEST_APP_SECRET);
        mCastScreenManager = CastScreenManager.getInstance();
        mCastScreenManager.setListener(new CastScreenManager.AListener() {
            @Override
            public void onInit(boolean success) {
                dismissDialog();
                ToastUtils.showLong(success ? getString(R.string.init_suc) : getString(R.string.init_def));
                if (success) {
                    Content.IsInit = true;
                    isSearch = true;
                    showDialog(getString(R.string.search_ing));
                    mCastScreenManager.startBrowse();
                } else {
                    Content.IsInit = false;
                }
            }

            @Override
            public void onBrowse(int code, List<LelinkServiceInfo> list) {
                dismissDialog();
                isSearch = false;
                if (code == IBrowseListener.BROWSE_SUCCESS) {
                    if (deviceAdapter != null) {
                        mDataBinding.tvDeviceNoData.setVisibility(View.GONE);
                        mDataBinding.rvDeviceList.setVisibility(View.VISIBLE);
                        deviceAdapter.setList(list);
                        //回显连接状态
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getName().equals(Content.ConnectName)) {
                                list.get(i).setConnect(true);
                            }
                        }
                        deviceAdapter.notifyDataSetChanged();
                    } else {
                        mDataBinding.tvAudioNoData.setVisibility(View.VISIBLE);
                        mDataBinding.rvDeviceList.setVisibility(View.GONE);
                    }
                } else if (code == IBrowseListener.BROWSE_TIMEOUT) {
                    ToastUtils.showLong(R.string.search_over);
                } else if (code == IBrowseListener.BROWSE_ERROR_AUTH || code == IBrowseListener.BROWSE_ERROR_AUTH_TIME) {
                    ToastUtils.showLong(R.string.auth_def);
                }
            }

            @Override
            public void onConnect(LelinkServiceInfo lelinkServiceInfo, int connectType) {
                String strProtocol = getString(R.string.no_agreement);
                switch (connectType) {
                    case IConnectListener.TYPE_LELINK:
                        strProtocol = getString(R.string.lelian_agreement);
                        break;
                    case IConnectListener.TYPE_DLNA:
                        strProtocol = getString(R.string.dlna_agreement);
                        break;
                    case IConnectListener.TYPE_IM:
                        strProtocol = getString(R.string.im_agreement);
                        break;
                }
                if (lelinkServiceInfo.getName() != null && !TextUtils.isEmpty(lelinkServiceInfo.getName())) {
                    Content.IsConnect = true;
                    Content.ConnectName = lelinkServiceInfo.getName();
                } else {
                    Content.IsConnect = false;
                    Content.ConnectName = "";
                }
                ToastUtils.showLong(getString(R.string.conn_device) + lelinkServiceInfo.getName() + getString(R.string.agreement_to) + strProtocol);
            }

            @Override
            public void onDisconnect(LelinkServiceInfo lelinkServiceInfo, int what, int extra) {
                Content.IsConnect = false;
                String text = getString(R.string.break_device) + lelinkServiceInfo.getName();
                if (what == IConnectListener.WHAT_HARASS_WAITING) {// 防骚扰，等待用户确认
                    // 乐播投屏防骚扰等待消息
                    text = lelinkServiceInfo.getName() + getString(R.string.wait_right);
                } else if (what == IConnectListener.WHAT_DISCONNECT) {
                    switch (extra) {
                        case IConnectListener.EXTRA_HARASS_REJECT:// 防骚扰，用户拒绝投屏
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_refuse);
                            break;
                        case IConnectListener.EXTRA_HARASS_TIMEOUT:// 防骚扰，用户响应超时
                            text = lelinkServiceInfo.getName() + getString(R.string.saorao_request_over);
                            break;
                        case IConnectListener.EXTRA_HARASS_BLACKLIST:// 防骚扰，该用户被加入黑名单
                            text = lelinkServiceInfo.getName() + getString(R.string.black_list);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_break);
                            break;
                    }
                } else if (what == IConnectListener.WHAT_CONNECT_FAILED) {
                    switch (extra) {
                        case IConnectListener.EXTRA_CONNECT_DEVICE_OFFLINE:
                            text = lelinkServiceInfo.getName() + getString(R.string.no_online);
                            break;
                        default:
                            text = lelinkServiceInfo.getName() + getString(R.string.conn_def);
                            break;
                    }
                }
                ToastUtils.showLong(text);
            }
        });
        if (!Content.IsInit) {
            showDialog(getString(R.string.init_ing));
            mCastScreenManager.init();
        }
    }

    private void clearSelection(){
        mDataBinding.tvVideoRecord.setTypeface(Typeface.DEFAULT);
        mDataBinding.tvVideoRecord.setTextColor(Color.parseColor("#80FFFFFF"));
        mDataBinding.ivVideoRecord.setVisibility(View.GONE);
        mDataBinding.rlVideoRecord.setVisibility(View.GONE);
        mDataBinding.tvPicRecord.setTypeface(Typeface.DEFAULT);
        mDataBinding.tvPicRecord.setTextColor(Color.parseColor("#80FFFFFF"));
        mDataBinding.ivPicRecord.setVisibility(View.GONE);
        mDataBinding.rlPicRecord.setVisibility(View.GONE);
        mDataBinding.tvAudioRecord.setTypeface(Typeface.DEFAULT);
        mDataBinding.tvAudioRecord.setTextColor(Color.parseColor("#80FFFFFF"));
        mDataBinding.ivAudioRecord.setVisibility(View.GONE);
        mDataBinding.rlAudioRecord.setVisibility(View.GONE);
    }

    //清空弹框
    private void clearDialog() {
        myClearDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_clear, null);
        myClearDialog.setContentView(inflate);
        myClearDialog.setCancelable(true);
        //获取当前Activity所在的窗体
        Window dialogWindow = myClearDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.9);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView dialogConfirm = inflate.findViewById(R.id.ivDialogClearConfirm);
        ImageView dialogCancel = inflate.findViewById(R.id.ivDialogClearCancel);
        dialogConfirm.setOnClickListener(this);
        dialogCancel.setOnClickListener(this);
    }

}